package www.shuang.common.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import www.shuang.users.pojo.AAdmins;
import www.shuang.users.pojo.AUsers;
import www.shuang.users.service.IAAdminsService;

@Controller
public class NoLoginController extends BaseController
{	@Resource
	private IAAdminsService adminsService;
	//打开管理员登录界面
	
	@RequestMapping("/adminsLogin.htm")
	public String adminsLogin(HttpServletRequest request){
		HttpSession session=request.getSession();
		AAdmins admins=(AAdmins) session.getAttribute("admins");
			if(admins != null){
				return "redirect://back/admins/index.htm";
			}
		return "/back/adminsLogin";
	}
	
	//管理员登陆提交页面
	@RequestMapping("/adminsLoginSubmit.htm")
	public String adminsLoginSubmit(HttpServletRequest request,String email,String password,String code){
		
		HttpSession session=request.getSession();
		
		//获取验证码
		String stringCode=session.getAttribute("code")+"";
		//将当前验证码移除
		session.removeAttribute(code);
		if(stringCode != null&&stringCode.equalsIgnoreCase(code)){
			
			Map<String,Object> condMap=new HashMap<String,Object>();
			condMap.put("email", email);
			AAdmins admins=this.adminsService.findOneAAdminsService(condMap);
			//用户名正常
			if(admins != null){
				//密码正确
				if(this.encryptUtil.checkPassword(password,admins.getPassword())){
					if(admins.getStatus() == 1){
						//跳转页面，更新上次登录时间
						session.setAttribute("admins", admins);
						session.setAttribute("lastLoginTime", admins.getLastLoginTime());
						admins.setLastLoginTime(new Date());
						//页面跳转
						return "redirect:/back/admins/index.htm";
					}else{
						this.info="账户被禁用";
					}
				}else{
					this.info="密码不正确";
				}
			}else{
				this.info="邮箱不存在";
			}
		}else{
			this.info="验证码错误";
		}
		
		
		request.setAttribute("info", info);
		return this.adminsLogin(request);
	}
	
	@RequestMapping("/login.htm")
	public String login(){
		
		return "/head/login";
	}
	
	@RequestMapping("/loginSubmit.htm")
	public String loginSubmit(HttpServletRequest request){
		HttpSession session=request.getSession();
		String email=request.getParameter("email");
		Map<String,Object> condMap=new HashMap<String,Object>();
		condMap.put("email", email);
		AUsers users = this.adminsService.findOneAUsersService(condMap);
		if(users != null)
		{
			session.setAttribute("users", users);
			
			return "redirect:/head/users/index.htm";
		}else {
			this.info="登陆失败";
		}
		request.setAttribute("info", info);
		return this.login();
	}
}
